package com.example.controller;

import com.example.common.AppResult;
import com.example.common.ResultCode;
import com.example.config.AppConfig;
import com.example.model.Message;
import com.example.model.User;
import com.example.service.IMessageService;
import com.example.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-10-20
 * Time: 15:24
 */
@Tag(name = "站内信接口")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IUserService userService;

    /**
     * 创建站内信
     * @param request 请求对象
     * @param receiveUserId 接收用户id
     * @param content 发送内容
     */
    @Operation(summary = "创建站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest  request,
                            @Parameter(description = "接收用户id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                            @Parameter(description = "发送内容") @RequestParam("content") @NonNull String content) {
        //1.获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.不能给自己发站内信
        if(user.getId().equals(receiveUserId)){
            //打印日志
            log.warn("不能给自己发送站内信，postUserId="+user.getId()+",receiveUserId="+receiveUserId);
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        //3.判断接收用户是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if(receiveUser == null || receiveUser.getDeleteState() == 1){
            //打印日志
            log.warn("接收站内信用户状态异常,receiveUserId="+receiveUserId);
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //4.创建站内信
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        //5.插入站内信信息到数据库中
        messageService.create(message);
        //6.返回成功信息
        return AppResult.success();
    }
    /**
     * 查询用户未读站内信数量
     * @param request 请求对象
     */
    @Operation(summary = "查询用户未读站内信数量")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        //1.获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user == null || user.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.查询用户未读站内信数量
        Integer count = messageService.selectUnreadCount(user.getId());
        //3.返回结果
        return AppResult.success(count);
    }
    /**
     * 查询用户所有站内信
     * @param request 请求对象
     */
    @Operation(summary = "查询用户所有站内信")
    @GetMapping("/getAll")
    public AppResult<List< Message>> getAll(HttpServletRequest request) {
        //1.获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user == null || user.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.查询用户所有站内信
        List<Message> list = messageService.selectByReceiveUserId(user.getId());
        //3.返回结果
        return AppResult.success(list);
    }
    /**
     * 修改站内信状态
     * @param request 请求对象
     * @param id 站内信id
     */
    @Operation(summary = "修改站内信状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @Parameter(description = "站内信id") @RequestParam("id") @NonNull Long id) {
        //1.根据id查询站内信
        Message message = messageService.selectById(id);
        //2.判断站内信是否存在
        if(message == null || message.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //3.判断站内信是不是本人的，本人不能查询别人的站内信
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(!message.getReceiveUserId().equals(user.getId())){
            //打印日志
            log.warn("查询了不属于自己的站内信：userId="+user.getId()+",receiveUserId="+message.getReceiveUserId());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //4.修改站内信状态为已读
        messageService.updateStateById(id, (byte) 1);
        //5.返回成功信息
        return AppResult.success();
    }
    /**
     * 回复站内信
     * @param request 请求对象
     * @param repliedId 站内信id
     * @param content 回复内容
     */
    @Operation(summary = "回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
             @Parameter(description = "站内信id") @RequestParam("repliedId") @NonNull Long repliedId,
             @Parameter(description = "回复内容") @RequestParam("content") @NonNull String content){
        //1.校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            //表示用户被禁言，不能回复站内信
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.校验站内信状态
        Message message = messageService.selectById(repliedId);
        if(message == null || message.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //不能回复自己的站内信
        if(message.getPostUserId().equals(user.getId())){
            log.warn("不能回复自己的站内信：userId="+user.getId());
            return AppResult.failed("不能回复自己的站内信");
        }
        //3.构造回复站内信对象
        Message replyMessage = new Message();
        replyMessage.setPostUserId(user.getId());
        replyMessage.setReceiveUserId(message.getPostUserId());
        replyMessage.setContent(content);
        //4.插入回复站内信
        messageService.reply(repliedId, replyMessage);
        //5.返回成功信息
        return AppResult.success();
    }
}
